package com.yami.shop.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.model.TbVersion;
import com.yami.shop.common.bean.PageDTO;
import com.yami.shop.common.bean.PageVO;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.dao.TbVersionMapper;
import com.yami.shop.service.VersionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class VersionServiceImpl extends ServiceImpl<TbVersionMapper, TbVersion> implements VersionService {

    @Autowired
    private TbVersionMapper tbVersionMapper;

    @Override
    public PageVO<TbVersion> getList(PageDTO pageDTO) {
        PageVO<TbVersion> retPage = new PageVO<>();
        IPage<TbVersion> iPage = new Page<>(pageDTO.getPageNum(),pageDTO.getPageSize());
        IPage<TbVersion> page = tbVersionMapper.selectPage(iPage, new QueryWrapper<TbVersion>().orderByDesc("creat_time"));
        retPage.setList(page.getRecords());
        retPage.setPages((int)page.getPages());
        retPage.setTotal(page.getTotal());

        return retPage;
    }

    @Override
    public void saveVersion(TbVersion tbVersion) {
        TbVersion version = tbVersionMapper.selectOne(Wrappers.lambdaQuery(TbVersion.class).eq(TbVersion::getStatus, "1").eq(TbVersion::getType,tbVersion.getType()));
        if(ObjectUtil.isNull(version)){
            version.setVersion("0");
        }
        //版本号转换
        int ageVersion = Integer.parseInt(version.getVersion().replace(".", ""));
        int AtVersion = Integer.parseInt(tbVersion.getVersion().replace(".", ""));
        if(AtVersion < ageVersion){
            throw new YamiShopBindException("版本小于当前版本");
        }
        tbVersionMapper.update(null,new LambdaUpdateWrapper<TbVersion>().set(TbVersion::getStatus,"0").eq(TbVersion::getStatus,"1"));
        tbVersionMapper.insert(tbVersion);
    }

    @Override
    public JSONObject getVersion(String type) {
        JSONObject jsonObject = new JSONObject();
        TbVersion version = tbVersionMapper.selectOne(Wrappers.lambdaQuery(TbVersion.class).eq(TbVersion::getStatus,1).eq(TbVersion::getType,type).orderByDesc(TbVersion::getCreatTime).last("limit 1 "));
        if(ObjectUtil.isNotEmpty(version)){
            jsonObject.set("version",version.getVersion());
            jsonObject.set("wgt",version.getWgt());
            jsonObject.set("detail",version.getDetail());
            jsonObject.set("versionOption",version.getVersionOption());
        }
        return jsonObject;
    }
}
